﻿using System;
using System.Data;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Web;
using System.Web.UI.WebControls;
using System.Collections.Specialized;
using System.Web.Security;
using System.Web.UI;
using System.Net;
using System.Net.Mail;
using System.Xml;
using System.Security.Cryptography;
using System.IO;

namespace ThuVien
{
    public static class FunctionsUtils
    {
        public static string ErrorMessage = string.Empty;

        /// <summary>
        /// 
        /// </summary>
        /// <param name="o"></param>
        /// <param name="defaultValue"></param>
        /// <returns></returns>
        public static int ConvertToInt(object o, int defaultValue)
        {
            try
            {
                if (o != null || Convert.IsDBNull(o) == false)
                    return int.Parse(o.ToString());
                return defaultValue;
            }
            catch
            {
                return defaultValue;
            }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="o"></param>
        /// <param name="defaultValue"></param>
        /// <returns></returns>
        public static long ConvertToLong(object o, long defaultValue)
        {
            try
            {
                if (o != null || Convert.IsDBNull(o) == false)
                    return long.Parse(o.ToString());
                return defaultValue;
            }
            catch
            {
                return defaultValue;
            }
        }

        public static decimal ConvertToDecimal(object o, decimal defaultValue)
        {
            try
            {
                if (o != null || Convert.IsDBNull(o) == false)
                    return decimal.Parse(o.ToString());
                return defaultValue;
            }
            catch
            {
                return defaultValue;
            }
        }

        public static double ConvertToDouble(object o, double defaultValue)
        {
            try
            {
                if (o != null || Convert.IsDBNull(o) == false)
                    return double.Parse(o.ToString());
                return defaultValue;
            }
            catch
            {
                return defaultValue;
            }
        }

        public static float ConvertToFloat(object o, float defaultValue)
        {
            try
            {
                if (o != null || Convert.IsDBNull(o) == false)
                    return float.Parse(o.ToString());
                return defaultValue;
            }
            catch
            {
                return defaultValue;
            }
        }

        public static bool ConvertToBool(object o, bool defaultValue)
        {
            if (o == null || Convert.IsDBNull(o) == true)
                return defaultValue;
            bool result = false;
            switch (o.ToString().ToLower())
            {
                case "1":
                case "true":
                    result = true;
                    break;
                case "0":
                case "false":
                    result = false;
                    break;
                default:
                    result = defaultValue;
                    break;
            }
            return result;
        }

        public static string ConvertToString(object o, string defaultValue)
        {
            if (o == null || Convert.IsDBNull(o) == true)
                return defaultValue;
            return Convert.ToString(o);
        }

        public static string GetAppPath()
        {
            string str = System.AppDomain.CurrentDomain.BaseDirectory.Replace("/", "\\");
            int i = str.IndexOf("\\bin\\");
            if (i > 0)
            {
                str = str.Substring(0, i + 1);
            }
            return str;
        }

        #region Web

        /// <summary>
        /// 
        /// </summary>
        /// <param name="ConfigKeyName"></param>
        /// <returns></returns>
        public static string GetConfigValue(string ConfigKeyName)
        {
            if (System.Configuration.ConfigurationManager.AppSettings[ConfigKeyName] != null)
                return System.Configuration.ConfigurationManager.AppSettings[ConfigKeyName].ToString();
            else
            {
                return string.Empty;
                //throw new ArgumentException("a key with the name " + ConfigKeyName + " doesn't exists in the current configurations", ConfigKeyName);
            }
        }

        public static Control FindControlInHeader(this Repeater repeater, string controlName)
        {
            return repeater.Controls[0].Controls[0].FindControl(controlName);
        }

        public static Control FindControlInFooter(this Repeater repeater, string controlName)
        {
            return repeater.Controls[repeater.Controls.Count - 1].Controls[0].FindControl(controlName);
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="listControl"></param>
        /// <param name="DataSource"></param>
        /// <param name="ValueField"></param>
        /// <param name="TextField"></param>
        public static void BindDataForControlList(ListControl listControl, object DataSource, string ValueField, string TextField)
        {
            if (listControl == null)
                return;
            try
            {
                listControl.DataTextField = TextField;
                listControl.DataValueField = ValueField;
                listControl.DataSource = DataSource;
                listControl.DataBind();
            }
            catch { }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="listControl"></param>
        /// <param name="ItemSelect"></param>
        /// <param name="selectBy"></param>
        public static void SelectItemInControlList(ListControl listControl, string ItemSelect, SelectBy selectBy)
        {
            try
            {
                if (listControl == null)
                    return;

                int vitri = 0;

                switch (selectBy)
                {
                    case SelectBy.Index:
                        vitri = int.Parse(ItemSelect);
                        break;
                    case SelectBy.Text:
                        vitri = (int)listControl.Items.IndexOf(listControl.Items.FindByText(ItemSelect));
                        break;
                    case SelectBy.Value:
                        vitri = (int)listControl.Items.IndexOf(listControl.Items.FindByValue(ItemSelect));
                        break;
                }
                listControl.SelectedIndex = vitri;
            }
            catch { }

        }

        public static int FindItemInControlList(ListControl listControl, string ItemSelect, SelectBy selectBy)
        {
            int vitri = -1;
            try
            {
                switch (selectBy)
                {
                    case SelectBy.Index:
                        if (int.Parse(ItemSelect) <= listControl.Items.Count)
                        {
                            vitri = int.Parse(ItemSelect);
                        }
                        break;
                    case SelectBy.Text:
                        vitri = listControl.Items.IndexOf(listControl.Items.FindByText(ItemSelect));
                        break;
                    case SelectBy.Value:
                        vitri = listControl.Items.IndexOf(listControl.Items.FindByValue(ItemSelect));
                        break;
                }
            }
            catch { }
            return vitri;
        }

        public static void AddItemsToAnotherListBoxAndDeleteIt(ListBox lbSource, ListBox lbDestination, bool MoveAll)
        {
            if (MoveAll == false)
            {
                for (int i = lbSource.GetSelectedIndices().Length - 1; i >= 0; i--)
                {
                    lbDestination.Items.Add(lbSource.Items[i]);
                    lbSource.Items.RemoveAt(i);
                }
            }
            else
            {
                for (int i = 0; i < lbSource.Items.Count; i++)
                {
                    lbDestination.Items.Add(lbSource.Items[i]);
                }
                lbSource.Items.Clear();
            }
        }

        public static string ConvertFromListBoxToStringList(ListBox lb)
        {
            string s = string.Empty;

            for (int i = 0; i < lb.Items.Count; i++)
            {
                s += string.Format("{0},", lb.Items[i].Value);
            }
            return s.TrimEnd(',');
        }

        public static int GetValueIntFromQueryString(string QueryStringName, int defaultValue)
        {
            return FunctionsUtils.ConvertToInt(System.Web.HttpContext.Current.Request[QueryStringName], defaultValue);
        }

        public static long GetValueLongFromQueryString(string QueryStringName, long defaultValue)
        {
            return FunctionsUtils.ConvertToLong(System.Web.HttpContext.Current.Request[QueryStringName], defaultValue);
        }

        public static double GetValueDoubleFromQueryString(string QueryStringName, double defaultValue)
        {
            return FunctionsUtils.ConvertToDouble(System.Web.HttpContext.Current.Request[QueryStringName], defaultValue);
        }

        public static decimal GetValueDecimalFromQueryString(string QueryStringName, decimal defaultValue)
        {
            return FunctionsUtils.ConvertToDecimal(System.Web.HttpContext.Current.Request[QueryStringName], defaultValue);
        }

        public static float GetValueDecimalFromQueryString(string QueryStringName, float defaultValue)
        {
            return FunctionsUtils.ConvertToFloat(System.Web.HttpContext.Current.Request[QueryStringName], defaultValue);
        }

        public static string GetValueStringFromQueryString(string QueryStringName, string defaultValue)
        {
            return FunctionsUtils.ConvertToString(System.Web.HttpContext.Current.Request[QueryStringName], defaultValue);
        }

        public static bool GetValueBoolFromQueryString(string QueryStringName, bool defaultValue)
        {
            return FunctionsUtils.ConvertToBool(System.Web.HttpContext.Current.Request[QueryStringName], defaultValue);
        }

        public static string GetPageName()
        {
            return System.IO.Path.GetFileName(System.Web.HttpContext.Current.Request.Url.AbsolutePath);


            //string pageName = System.Web.HttpContext.Current.Request.Url.AbsolutePath;

            //int pos = pageName.IndexOf('?');
            //if (pos >= 0)
            //    pageName = pageName.Substring(0, pos);
            //pos = pageName.LastIndexOf('/');
            //if (pos >= 0)
            //    pageName = pageName.Substring(pos + 1);
            //return pageName;
        }

        public static string GetPageTitle()
        {
            string s = string.Empty;
            string PageName = GetPageName();
            SiteMapNodeCollection nodes = SiteMap.Provider.GetChildNodes(SiteMap.RootNode);
            foreach (SiteMapNode node in nodes)
            {
                if (node.ResourceKey != null && node.ResourceKey.ToLower() == PageName.ToLower())
                {
                    s = (node.Title != string.Empty) ? node.Title : string.Empty;
                    break;
                }
            }
            return s;
        }

        public static string HTMLEncode(object o)
        {
            if (IsNullOrEmpty(o) == true)
                return string.Empty;
            return System.Web.HttpContext.Current.Server.HtmlEncode(o.ToString());
        }

        public static string HTMLDecode(object o)
        {
            if (IsNullOrEmpty(o) == true)
                return string.Empty;
            return System.Web.HttpContext.Current.Server.HtmlDecode(o.ToString());
        }

        public static void ShowSmallError(Literal lt, string ErrorMsg)
        {
            lt.Text = string.Format("<span class='msgErrorSmall' id='{0}'>{1}</span>", lt.ClientID, ErrorMsg);
        }

        public static void ShowSmallError(Label lb, string ErrorMsg)
        {
            lb.Text = ErrorMsg;
            lb.CssClass = "msgErrorSmall";
        }

        public static void AssignText(TextBox[] tb, System.Data.DataRow row, string[] fields)
        {
            for (int i = 0; i < tb.Length; i++)
            {
                tb[i].Text = ConvertToString(row[fields[i]], string.Empty);
            }
        }

        /// <summary>
        /// check Required & CorrectFormat
        /// </summary>
        /// <param name="tb"></param>
        /// <param name="lr"></param>
        /// <param name="IsRequired"></param>
        /// <param name="fmt"></param>
        /// <param name="msgRequired"></param>
        /// <param name="msgInValid"></param>
        /// <returns></returns>
        public static bool InputValid(TextBox[] tb, Literal[] lt, bool[] IsRequired, FormatType[] fmt, string msgRequired, string msgInValid)
        {
            bool IsValid = true;
            for (int i = 0; i < tb.Length; i++)
            {
                tb[i].Text = tb[i].Text.Trim();
                if (IsRequired[i] && tb[i].Text == string.Empty)
                {
                    ShowSmallError(lt[i], msgRequired);
                    IsValid = false;
                    continue;
                }

                if (fmt[i] != FormatType.None && tb[i].Text != string.Empty)
                {
                    switch (fmt[i])
                    {
                        case FormatType.UserName:
                            if (!ValidateUtils.isUserName(tb[i].Text))
                            {
                                //lt[i].Text = msgInValid;
                                ShowSmallError(lt[i], msgInValid);
                                IsValid = false;
                            }
                            break;
                        case FormatType.Password:
                            if (!ValidateUtils.isAlphaNumeric(tb[i].Text))
                            {
                                //lt[i].Text = msgInValid;
                                ShowSmallError(lt[i], msgInValid);
                                IsValid = false;
                            }
                            break;
                        case FormatType.USPhone:
                            if (!ValidateUtils.isUSPhone(tb[i].Text))
                            {
                                //lt[i].Text = msgInValid;
                                ShowSmallError(lt[i], msgInValid);
                                IsValid = false;
                            }
                            break;
                        case FormatType.USZip:
                            if (!ValidateUtils.isUSZipCode(tb[i].Text))
                            {
                                //lt[i].Text = msgInValid;
                                ShowSmallError(lt[i], msgInValid);
                                IsValid = false;
                            }
                            break;
                        case FormatType.Email:
                            if (!ValidateUtils.isEmail(tb[i].Text))
                            {
                                //lt[i].Text = msgInValid;
                                ShowSmallError(lt[i], msgInValid);
                                IsValid = false;
                            }
                            break;
                        case FormatType.Int:
                            if (!ValidateUtils.isNumber(tb[i].Text, NumberType.Integer))
                            {
                                //lt[i].Text = msgInValid;
                                ShowSmallError(lt[i], msgInValid);
                                IsValid = false;
                            }
                            break;
                        case FormatType.Double:
                            if (!ValidateUtils.isNumber(tb[i].Text, NumberType.Double))
                            {
                                //lt[i].Text = msgInValid;
                                ShowSmallError(lt[i], msgInValid);
                                IsValid = false;
                            }
                            break;
                        case FormatType.Decimal:
                            if (ValidateUtils.isNumber(tb[i].Text, NumberType.Decimal) == false)
                            {
                                ShowSmallError(lt[i], msgInValid);
                                IsValid = false;
                            }
                            break;
                        case FormatType.NumberLetter:
                            if (ValidateUtils.isNumberLetter(tb[i].Text) == false)
                            {
                                ShowSmallError(lt[i], msgInValid);
                                IsValid = false;
                            }
                            break;
                        case FormatType.CreditCard:
                            if (ValidateUtils.isCreditCard(tb[i].Text) == false)
                            {
                                ShowSmallError(lt[i], msgInValid);
                                IsValid = false;
                            }
                            break;
                        default:
                            break;
                    }
                }
            }
            return IsValid;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="lt"></param>
        public static void clearText(Literal[] lt)
        {
            for (int i = 0; i < lt.Length; i++)
                lt[i].Text = string.Empty;
        }

        /// <summary>
        /// tao MailMessage de goi email
        /// </summary>
        /// <param name="From"></param>
        /// <param name="To"></param>
        /// <param name="Subject"></param>
        /// <param name="Body"></param>
        /// <param name="IsBodyHTMLFormat"></param>
        /// <param name="CC"></param>
        /// <param name="Bcc"></param>
        /// <returns></returns>
        private static MailMessage CreateMailMessage(string From, string To, string Subject, string Body, bool IsBodyHTMLFormat, string CC, string Bcc, string fileAttachment)
        {
            MailMessage mail = new MailMessage();
            //add the email address we will be sending the message to
            mail.To.Add(To);
            //add our email here
            mail.From = new MailAddress(From);

            //if (string.IsNullOrEmpty(CC) == false)
            //{
            //    mail.CC.Add(CC);
            //}

            //if (string.IsNullOrEmpty(Bcc) == false)
            //{
            //    mail.Bcc.Add(Bcc);
            //}

            //if (System.IO.File.Exists(fileAttachment) == true)
            //{
            //    mail.Attachments.Add(new Attachment(fileAttachment));
            //}

            //email's subject
            mail.Subject = Subject;
            mail.Body = Body;
            mail.BodyEncoding = System.Text.Encoding.UTF8;
            mail.IsBodyHtml = IsBodyHTMLFormat;

            return mail;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="From"></param>
        /// <param name="To"></param>
        /// <param name="Subject"></param>
        /// <param name="Body"></param>
        /// <param name="IsBodyHTMLFormat"></param>
        /// <param name="CC"></param>
        /// <param name="Bcc"></param>
        /// <returns></returns>
        private static MailMessage CreateMailMessage(string From, string[] To, string Subject, string Body, bool IsBodyHTMLFormat, string CC, string Bcc, string fileAttachment)
        {
            MailMessage mail = new MailMessage();
            //add the email address we will be sending the message to
            for (int i = 0; i < To.Length; i++)
            {
                mail.To.Add(To[i]);
            }
            //add our email here
            mail.From = new MailAddress(From);

            if (string.IsNullOrEmpty(CC) == false)
            {
                mail.CC.Add(CC);
            }

            if (string.IsNullOrEmpty(Bcc) == false)
            {
                mail.Bcc.Add(Bcc);
            }

            if (System.IO.File.Exists(fileAttachment) == true)
            {
                mail.Attachments.Add(new Attachment(fileAttachment));
            }

            //email's subject
            mail.Subject = Subject; //"Thank you for registering as a Merchant";
            mail.Body = Body;
            mail.BodyEncoding = System.Text.Encoding.UTF8;
            mail.IsBodyHtml = IsBodyHTMLFormat;

            return mail;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="From"></param>
        /// <param name="To"></param>
        /// <param name="Subject"></param>
        /// <param name="Body"></param>
        /// <param name="IsBodyHTMLFormat"></param>
        /// <param name="CC"></param>
        /// <param name="Bcc"></param>
        /// <param name="fileAttachment"></param>
        /// <returns></returns>
        private static MailMessage CreateMailMessage(string From, string[] To, string Subject, string Body, bool IsBodyHTMLFormat, string CC, string Bcc, string[] fileAttachment)
        {
            MailMessage mail = new MailMessage();
            //add the email address we will be sending the message to
            for (int i = 0; i < To.Length; i++)
            {
                mail.To.Add(To[i]);
            }
            //add our email here
            mail.From = new MailAddress(From);

            if (string.IsNullOrEmpty(CC) == false)
            {
                mail.CC.Add(CC);
            }

            if (string.IsNullOrEmpty(Bcc) == false)
            {
                mail.Bcc.Add(Bcc);
            }

            for (int i = 0; i < fileAttachment.Length; i++)
            {
                if (System.IO.File.Exists(fileAttachment[i]) == true)
                {
                    mail.Attachments.Add(new Attachment(fileAttachment[i]));
                }
            }

            //email's subject
            mail.Subject = Subject; //"Thank you for registering as a Merchant";
            mail.Body = Body;
            mail.BodyEncoding = System.Text.Encoding.UTF8;
            mail.IsBodyHtml = IsBodyHTMLFormat;

            return mail;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="From"></param>
        /// <param name="To"></param>
        /// <param name="Subject"></param>
        /// <param name="Body"></param>
        /// <param name="IsBodyHTMLFormat"></param>
        /// <param name="CC"></param>
        /// <param name="Bcc"></param>
        /// <param name="fileAttachment"></param>
        /// <returns></returns>
        private static MailMessage CreateMailMessage(string From, string To, string Subject, string Body, bool IsBodyHTMLFormat, string CC, string Bcc, string[] fileAttachment)
        {
            MailMessage mail = new MailMessage();
            //add the email address we will be sending the message to
            mail.To.Add(To);

            //add our email here
            mail.From = new MailAddress(From);

            if (string.IsNullOrEmpty(CC) == false)
            {
                mail.CC.Add(CC);
            }

            if (string.IsNullOrEmpty(Bcc) == false)
            {
                mail.Bcc.Add(Bcc);
            }

            for (int i = 0; i < fileAttachment.Length; i++)
            {
                if (System.IO.File.Exists(fileAttachment[i]) == true)
                {
                    mail.Attachments.Add(new Attachment(fileAttachment[i]));
                }
            }

            //email's subject
            mail.Subject = Subject; //"Thank you for registering as a Merchant";
            mail.Body = Body;
            mail.BodyEncoding = System.Text.Encoding.UTF8;
            mail.IsBodyHtml = IsBodyHTMLFormat;

            return mail;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="MailServer"></param>
        /// <param name="From"></param>
        /// <param name="To"></param>
        /// <param name="Subject"></param>
        /// <param name="Body"></param>
        /// <param name="IsBodyHTMLFormat"></param>
        public static int SendEmail(string MailServer, string From, string To, string Subject, string Body, bool IsBodyHTMLFormat)
        {
            try
            {
                SmtpClient client = new SmtpClient();
                client.Host = MailServer;

                client.Send(CreateMailMessage(From, To, Subject, Body, IsBodyHTMLFormat, string.Empty, string.Empty, string.Empty));
                return 0;
            }
            catch
            {
                return -1;
            }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="MailServer"></param>
        /// <param name="From"></param>
        /// <param name="To"></param>
        /// <param name="Subject"></param>
        /// <param name="Body"></param>
        /// <param name="IsBodyHTMLFormat"></param>
        /// <param name="fileAttachment"></param>
        /// <returns></returns>
        public static int SendEmail(string MailServer, string From, string To, string Subject, string Body, bool IsBodyHTMLFormat, string fileAttachment)
        {
            try
            {
                SmtpClient client = new SmtpClient();
                client.Host = MailServer;

                client.Send(CreateMailMessage(From, To, Subject, Body, IsBodyHTMLFormat, string.Empty, string.Empty, fileAttachment));
                return 0;
            }
            catch
            {
                return -1;
            }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="MailServer"></param>
        /// <param name="From"></param>
        /// <param name="To"></param>
        /// <param name="Subject"></param>
        /// <param name="Body"></param>
        /// <param name="IsBodyHTMLFormat"></param>
        public static int SendEmail(string MailServer, string From, string[] To, string Subject, string Body, bool IsBodyHTMLFormat)
        {
            try
            {
                SmtpClient client = new SmtpClient();
                client.Host = MailServer;

                client.Send(CreateMailMessage(From, To, Subject, Body, IsBodyHTMLFormat, string.Empty, string.Empty, string.Empty));
                return 0;
            }
            catch
            {
                return -1;
            }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="MailServer"></param>
        /// <param name="From"></param>
        /// <param name="To"></param>
        /// <param name="Subject"></param>
        /// <param name="Body"></param>
        /// <param name="IsBodyHTMLFormat"></param>
        public static int SendEmail(string MailServer, string From, string[] To, string Subject, string Body, bool IsBodyHTMLFormat, string[] fileAttachment)
        {
            try
            {
                SmtpClient client = new SmtpClient();
                client.Host = MailServer;

                client.Send(CreateMailMessage(From, To, Subject, Body, IsBodyHTMLFormat, string.Empty, string.Empty, fileAttachment));
                return 0;
            }
            catch
            {
                return -1;
            }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="MailServer"></param>
        /// <param name="From"></param>
        /// <param name="To"></param>
        /// <param name="Subject"></param>
        /// <param name="Body"></param>
        /// <param name="IsBodyHTMLFormat"></param>
        /// <param name="UseGmailServer"></param>
        /// <returns></returns>
        public static int SendEmail(string MailServer, string From, string To, string Subject, string Body, bool IsBodyHTMLFormat, bool UseGmailServer)
        {
            try
            {
                SmtpClient client = new SmtpClient();

                if (UseGmailServer == true)
                {
                    System.Net.NetworkCredential mailAuthentication = new System.Net.NetworkCredential("thichdaydu@gmail.com", "9511025");
                    client.Host = "smtp.gmail.com";
                    client.Port = 587;
                    client.EnableSsl = true;
                    client.UseDefaultCredentials = false;
                    client.Credentials = mailAuthentication;
                }
                else
                {
                    client.Host = MailServer;
                }
                client.Send(CreateMailMessage(From, To, Subject, Body, IsBodyHTMLFormat, string.Empty, string.Empty, string.Empty));
                return 0;
            }
            catch (Exception ex)
            {
                ErrorMessage = ex.Message;
                return -1;
            }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="MailServer"></param>
        /// <param name="From"></param>
        /// <param name="To"></param>
        /// <param name="Subject"></param>
        /// <param name="Body"></param>
        /// <param name="IsBodyHTMLFormat"></param>
        /// <param name="UseGmailServer"></param>
        /// <param name="fileAttachment"></param>
        /// <returns></returns>
        public static int SendEmail(string MailServer, string From, string To, string Subject, string Body, bool IsBodyHTMLFormat, bool UseGmailServer, string fileAttachment)
        {
            try
            {
                SmtpClient client = new SmtpClient();

                if (UseGmailServer == true)
                {
                    System.Net.NetworkCredential mailAuthentication = new System.Net.NetworkCredential("thichdaydu@gmail.com", "9511025");
                    client.Host = "smtp.gmail.com";
                    client.Port = 587;
                    client.EnableSsl = true;
                    client.UseDefaultCredentials = false;
                    client.Credentials = mailAuthentication;
                }
                else
                {
                    client.Host = MailServer;
                }

                client.Send(CreateMailMessage(From, To, Subject, Body, IsBodyHTMLFormat, string.Empty, string.Empty, fileAttachment));
                return 0;
            }
            catch
            {
                return -1;
            }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="MailServer"></param>
        /// <param name="From"></param>
        /// <param name="To"></param>
        /// <param name="Subject"></param>
        /// <param name="Body"></param>
        /// <param name="IsBodyHTMLFormat"></param>
        /// <param name="UseGmailServer"></param>
        /// <returns></returns>
        public static int SendEmail(string MailServer, string From, string[] To, string Subject, string Body, bool IsBodyHTMLFormat, bool UseGmailServer)
        {
            try
            {
                SmtpClient client = new SmtpClient();

                if (UseGmailServer == true)
                {
                    System.Net.NetworkCredential mailAuthentication = new System.Net.NetworkCredential("thichdaydu@gmail.com", "9511025");
                    client.Host = "smtp.gmail.com";
                    client.Port = 587;
                    client.EnableSsl = true;
                    client.UseDefaultCredentials = false;
                    client.Credentials = mailAuthentication;
                }
                else
                {
                    client.Host = MailServer;
                }

                client.Send(CreateMailMessage(From, To, Subject, Body, IsBodyHTMLFormat, string.Empty, string.Empty, string.Empty));
                return 0;
            }
            catch
            {
                return -1;
            }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="MailServer"></param>
        /// <param name="From"></param>
        /// <param name="To"></param>
        /// <param name="Subject"></param>
        /// <param name="Body"></param>
        /// <param name="IsBodyHTMLFormat"></param>
        /// <param name="UseGmailServer"></param>
        /// <param name="CC"></param>
        /// <param name="Bcc"></param>
        /// <param name="fileAttachment"></param>
        /// <returns></returns>
        public static int SendEmail(string MailServer, string From, string[] To, string Subject, string Body, bool IsBodyHTMLFormat, bool UseGmailServer, string CC, string Bcc, string[] fileAttachment)
        {
            try
            {
                SmtpClient client = new SmtpClient();

                if (UseGmailServer == true)
                {
                    System.Net.NetworkCredential mailAuthentication = new System.Net.NetworkCredential("thichdaydu@gmail.com", "9511025");
                    client.Host = "smtp.gmail.com";
                    client.Port = 587;
                    client.EnableSsl = true;
                    client.UseDefaultCredentials = false;
                    client.Credentials = mailAuthentication;
                }
                else
                {
                    client.Host = MailServer;
                }
                client.Send(CreateMailMessage(From, To, Subject, Body, IsBodyHTMLFormat, CC, Bcc, fileAttachment));
                return 0;
            }
            catch
            {
                return -1;
            }
        }

        #endregion

        #region string, format, encrypt
        /// <summary>
        /// Double Single Quote
        /// </summary>
        /// <param name="s">chuỗi cần xóa khoảng trắng</param>
        /// <returns>string</returns>
        public static string DoubleSingleQuote(Object s)
        {
            if (IsNullOrEmpty(s) == true)
                return string.Empty;
            return s.ToString().Trim().Replace("'", "''");
        }

        /// <summary>
        /// Xóa các khoảng trắng trước, sau chuỗi, 2 or nhiều khoảng trắng ở giữa chuỗi thành 1 khoảng trắng
        /// </summary>
        /// <param name="s"></param>
        /// <returns>Trả về một chuỗi được xóa các khoảng trắng.</returns>
        public static string TrimAll(Object s)
        {
            if (IsNullOrEmpty(s) == true)
                return string.Empty;
            return Regex.Replace(s.ToString().Trim(), "\\s+", " ");
        }

        /// <summary>
        /// Thay thế tất cả chuổi strFind mà nó tìm thấy
        /// </summary>
        /// <param name="s"></param>
        /// <param name="strFind">chuỗi tìm kiếm</param>
        /// <param name="strReplace">chuỗi thay thế</param>
        /// <returns>string được thay thế</returns>
        public static string ReplaceAll(Object s, string strFind, string strReplace)
        {
            string tmp = (IsNullOrEmpty(s) == true) ? string.Empty : s.ToString().Trim();
            if (tmp.Length > 0)
            {
                while (tmp.IndexOf(strFind) > 0)
                {
                    tmp = tmp.Replace(strFind, strReplace);
                }
            }
            return tmp.ToString();
        }

        /// <summary>
        /// Format ký tự đầu tiên của một từ thành chữ hoa
        /// </summary>
        /// <param name="s">string cần format</param>
        /// <returns>string</returns>
        public static string TitleCase(object s)
        {
            string strParam = (IsNullOrEmpty(s) == true) ? string.Empty : s.ToString().Trim();

            if (strParam.Length <= 0)
                return strParam;

            string strProper = strParam.Substring(0, 1).ToUpper();
            strParam = strParam.Substring(1).ToLower();
            string strPrev = string.Empty;

            for (int iIndex = 0; iIndex < strParam.Length; iIndex++)
            {
                if (iIndex > 1)
                    strPrev = strParam.Substring(iIndex - 1, 1);

                if (strPrev.Equals(" ") || strPrev.Equals("\t") || strPrev.Equals("\n") || strPrev.Equals("."))
                    strProper += strParam.Substring(iIndex, 1).ToUpper();
                else
                    strProper += strParam.Substring(iIndex, 1);
            }
            return strProper;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="s"></param>
        /// <returns></returns>
        public static string TitleCase(string s)
        {
            return System.Threading.Thread.CurrentThread.CurrentCulture.TextInfo.ToTitleCase(s);
        }

        /// <summary>
        /// Lấy ra 1 string từ trái qua phải theo một chiều dài của 1 string
        /// </summary>
        /// <param name="o">chuoi can cat</param>
        /// <param name="Length">chieu dai chuoi can lay</param>
        /// <returns></returns>
        public static string Left(object o, int Length)
        {
            string str = (IsNullOrEmpty(o) == true) ? string.Empty : o.ToString().Trim();

            if (Length < 0)
            {
                return string.Empty;
            }

            if ((Length == 0) || (str.Equals(string.Empty) == true))
            {
                return string.Empty;
            }

            if (Length >= str.Length)
            {
                return str;
            }

            return str.Substring(0, Length);
        }

        /// <summary>
        /// Lấy ra 1 string từ phải sang trái theo một chiều dài của 1 string
        /// </summary>
        /// <param name="o">chuoi can cat</param>
        /// <param name="Length">chieu dai chuoi can lay</param>
        /// <returns></returns>
        public static string Right(object o, int Length)
        {
            string str = (IsNullOrEmpty(o) == true) ? string.Empty : o.ToString().Trim();
            if (Length < 0)
            {
                return string.Empty;
            }
            if ((Length == 0) || (str.Equals(string.Empty) == true))
            {
                return string.Empty;
            }
            int length = str.Length;
            if (Length >= length)
            {
                return str;
            }
            return str.Substring(length - Length, Length);
        }

        public static string Mid(object o, int Start, int Length)
        {
            string str = (IsNullOrEmpty(o) == true) ? string.Empty : o.ToString().Trim();
            if (Start <= 0 || Length < 0)
            {
                return string.Empty;
            }

            if ((Length == 0) || (str.Equals(string.Empty) == true))
            {
                return string.Empty;
            }
            int length = str.Length;
            if (Start > length)
            {
                return string.Empty;
            }
            if ((Start + Length) > length)
            {
                return str.Substring(Start - 1);
            }
            return str.Substring(Start - 1, Length);
        }

        public static string Mid(object o, int Start)
        {
            string str = (IsNullOrEmpty(o) == true) ? string.Empty : o.ToString().Trim();

            try
            {
                if (str.Equals(string.Empty) == true)
                {
                    return string.Empty;
                }
                return Mid(str, Start, str.Length);
            }
            catch
            {
                return string.Empty;
            }
        }

        /// <summary>
        /// ham delete cac ky tu cua bag xuat hien trong chuoi theo 
        /// </summary>
        /// <param name="s">chuoi</param>
        /// <param name="bag">cac ky tu can xoa</param>
        /// <returns></returns>
        public static string stripCharsInBag(object s, string bag)
        {
            string tmp = (IsNullOrEmpty(s) == true) ? string.Empty : s.ToString().Trim();
            if (tmp.Length > 0)
            {
                try
                {
                    for (int i = 0; i <= bag.Length - 1; i++)
                    {
                        tmp = tmp.Replace(bag[i].ToString(), "");
                    }
                }
                catch { }
            }
            return tmp.ToString();
        }

        /// <summary>
        /// cat chuoi theo mot doan ma k bi cat ngang
        /// </summary>
        /// <param name="o"></param>
        /// <param name="Length"></param>
        /// <returns></returns>
        public static string CutString(object o, int Length)
        {
            if (IsNullOrEmpty(o) == true)
                return string.Empty;
            string s = o.ToString();
            if (Length > s.Length)
                return s;

            string tmp = s.Substring(0, Length);
            int vitri = 0;
            vitri = tmp.LastIndexOf(" ");
            if (vitri > 0)
            {
                //return s.Substring(0, vitri) + "<br>" + s.Substring(vitri + 1, s.Length - vitri - 1);
                //return s.Substring(0, vitri) + "<br>" + CutString(s.Substring(vitri + 1, s.Length - vitri - 1), Length);
                return s.Substring(0, vitri) + "...";
            }
            return s;
        }

        /// <summary>
        /// Microsoft
        /// </summary>
        /// <param name="value"></param>
        /// <returns></returns>
        public static bool IsNullOrEmpty(object value)
        {
            if (value == null || Convert.IsDBNull(value) == true)
                return true;

            return string.IsNullOrEmpty(value.ToString());
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="o"></param>
        /// <param name="delimiter"></param>
        /// <returns></returns>
        public static List<string> ConvertStringToList(object s, char delimiter)
        {
            if (IsNullOrEmpty(s) == true)
                return null;
            return new List<string>(s.ToString().Split(delimiter));
        }

        /// <summary>
        /// Ham dung ma hoa 1 chuoi khong co cho decrypt lai duoc
        /// </summary>
        /// <param name="s">chuoi can ma hoa</param>
        /// <param name="HashAlgorithm">co 2 loai ma hoa la md5 va sha1</param>
        /// <returns>tra ve 1 chuoi duoc ma hoa theo dang md5 or sha1</returns>
        public static string EncryptNonDecrypt(object s, HashAlgorithmMode HashAlgorithm)
        {
            if (IsNullOrEmpty(s) == true)
                return string.Empty;
            return System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(s.ToString(), HashAlgorithm.ToString());
        }

        /// <summary>
        /// ham dung de ma hoa mot chuoi
        /// </summary>
        /// <param name="s">chuoi can ma hoa</param>
        /// <returns>chuoi duoc ma hoa</returns>
        public static string Encrypt(object s)
        {
            CryptoLib crypt = new CryptoLib("du7o7c5 ro62i", CryptoServiceProvider.DES);
            return crypt.Encrypt(s);
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="s"></param>
        /// <param name="Key"></param>
        /// <param name="CryptoType"></param>
        /// <returns></returns>
        public static string Encrypt(object s, string Key, CryptoServiceProvider CryptoType)
        {
            CryptoLib crypt = new CryptoLib(Key, CryptoType);
            return crypt.Encrypt(s);
        }

        /// <summary>
        /// ham dung de decrypt lai mot chuoi da dc ma hoa
        /// </summary>
        /// <param name="s">chuoi duoc ma hoa</param>
        /// <returns>chuoi binh thuong</returns>
        public static string Decrypt(object s)
        {
            CryptoLib crypt = new CryptoLib("du7o7c5 ro62i", CryptoServiceProvider.DES);
            return crypt.Decrypt(s);
        }

        public static string DecryptWeb(object s)
        {
            string tmp = (s == null) ? string.Empty : s.ToString().Replace(" ", "+");
            return Decrypt(tmp);
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="s"></param>
        /// <param name="Key"></param>
        /// <param name="CryptoType"></param>
        /// <returns></returns>
        public static string Decrypt(object s, string Key, CryptoServiceProvider CryptoType)
        {
            CryptoLib crypt = new CryptoLib(Key, CryptoType);
            return crypt.Decrypt(s);
        }


        /// <summary>
        /// Creates a temporary password of a specified length.
        /// </summary>
        /// <param name="length">The maximum length of the temporary password to create.</param>
        /// <returns>A temporary password less than or equal to the length specified.</returns>
        public static string CreateTemporaryPassword(int length)
        {
            string strTempPassword = Guid.NewGuid().ToString("N");
            for (int i = 0; i < (length / 32); i++)
            {
                strTempPassword += Guid.NewGuid().ToString("N");
            }
            return strTempPassword.Substring(0, length);
        }

        public static string CreateRandomPass(int minLength, int maxLength)
        {
            string PASSWORD_CHARS_LCASE = "abcdefgijkmnopqrstwxyz";
            string PASSWORD_CHARS_UCASE = "ABCDEFGHJKLMNPQRSTWXYZ";
            string PASSWORD_CHARS_NUMERIC = "23456789";

            // Make sure that input parameters are valid.
            if (minLength <= 0 || maxLength <= 0 || minLength > maxLength)
                return null;

            // Create a local array containing supported password characters
            // grouped by types.
            char[][] charGroups = new char[][] 
		{
			PASSWORD_CHARS_LCASE.ToCharArray(),
			PASSWORD_CHARS_UCASE.ToCharArray(),
			PASSWORD_CHARS_NUMERIC.ToCharArray(),
			//PASSWORD_CHARS_SPECIAL.ToCharArray()
		};

            // Use this array to track the number of unused characters in each
            // character group.
            int[] charsLeftInGroup = new int[charGroups.Length];

            // Initially, all characters in each group are not used.
            for (int i = 0; i < charsLeftInGroup.Length; i++)
                charsLeftInGroup[i] = charGroups[i].Length;

            // Use this array to track (iterate through) unused character groups.
            int[] leftGroupsOrder = new int[charGroups.Length];

            // Initially, all character groups are not used.
            for (int i = 0; i < leftGroupsOrder.Length; i++)
                leftGroupsOrder[i] = i;

            // Because we cannot use the default randomizer, which is based on the
            // current time (it will produce the same "random" number within a
            // second), we will use a random number generator to seed the
            // randomizer.

            // Use a 4-byte array to fill it with random bytes and convert it then
            // to an integer value.
            byte[] randomBytes = new byte[4];

            // Generate 4 random bytes.
            RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider();
            rng.GetBytes(randomBytes);

            // Convert 4 bytes into a 32-bit integer value.
            int seed = (randomBytes[0] & 0x7f) << 24 |
                randomBytes[1] << 16 |
                randomBytes[2] << 8 |
                randomBytes[3];

            // Now, this is real randomization.
            Random random = new Random(seed);

            // This array will hold password characters.
            char[] password = null;

            // Allocate appropriate memory for the password.
            if (minLength < maxLength)
                password = new char[random.Next(minLength, maxLength + 1)];
            else
                password = new char[minLength];

            // Index of the next character to be added to password.
            int nextCharIdx;

            // Index of the next character group to be processed.
            int nextGroupIdx;

            // Index which will be used to track not processed character groups.
            int nextLeftGroupsOrderIdx;

            // Index of the last non-processed character in a group.
            int lastCharIdx;

            // Index of the last non-processed group. Initially, we will skip
            // special characters.
            int lastLeftGroupsOrderIdx = leftGroupsOrder.Length - 1;

            // Generate password characters one at a time.
            for (int i = 0; i < password.Length; i++)
            {
                // If only one character group remained unprocessed, process it;
                // otherwise, pick a random character group from the unprocessed
                // group list.
                if (lastLeftGroupsOrderIdx == 0)
                    nextLeftGroupsOrderIdx = 0;
                else
                    nextLeftGroupsOrderIdx = random.Next(0,
                        lastLeftGroupsOrderIdx);

                // Get the actual index of the character group, from which we will
                // pick the next character.
                nextGroupIdx = leftGroupsOrder[nextLeftGroupsOrderIdx];

                // Get the index of the last unprocessed characters in this group.
                lastCharIdx = charsLeftInGroup[nextGroupIdx] - 1;

                // If only one unprocessed character is left, pick it; otherwise,
                // get a random character from the unused character list.
                if (lastCharIdx == 0)
                    nextCharIdx = 0;
                else
                    nextCharIdx = random.Next(0, lastCharIdx + 1);

                // Add this character to the password.
                password[i] = charGroups[nextGroupIdx][nextCharIdx];

                // If we processed the last character in this group, start over.
                if (lastCharIdx == 0)
                    charsLeftInGroup[nextGroupIdx] =
                        charGroups[nextGroupIdx].Length;
                // There are more unprocessed characters left.
                else
                {
                    // Swap processed character with the last unprocessed character
                    // so that we don't pick it until we process all characters in
                    // this group.
                    if (lastCharIdx != nextCharIdx)
                    {
                        char temp = charGroups[nextGroupIdx][lastCharIdx];
                        charGroups[nextGroupIdx][lastCharIdx] =
                            charGroups[nextGroupIdx][nextCharIdx];
                        charGroups[nextGroupIdx][nextCharIdx] = temp;
                    }
                    // Decrement the number of unprocessed characters in
                    // this group.
                    charsLeftInGroup[nextGroupIdx]--;
                }

                // If we processed the last group, start all over.
                if (lastLeftGroupsOrderIdx == 0)
                    lastLeftGroupsOrderIdx = leftGroupsOrder.Length - 1;
                // There are more unprocessed groups left.
                else
                {
                    // Swap processed group with the last unprocessed group
                    // so that we don't pick it until we process all groups.
                    if (lastLeftGroupsOrderIdx != nextLeftGroupsOrderIdx)
                    {
                        int temp = leftGroupsOrder[lastLeftGroupsOrderIdx];
                        leftGroupsOrder[lastLeftGroupsOrderIdx] =
                            leftGroupsOrder[nextLeftGroupsOrderIdx];
                        leftGroupsOrder[nextLeftGroupsOrderIdx] = temp;
                    }
                    // Decrement the number of unprocessed groups.
                    lastLeftGroupsOrderIdx--;
                }
            }

            // Convert password characters into a string and return the result.
            return new string(password).ToLower();
        }

        /// <summary>
        /// Format US Zip Code Number
        /// </summary>
        /// <param name="s"></param>
        /// <returns></returns>
        public static string FormatUSZipCode(object s)
        {
            string tmp = (s == null) ? string.Empty : s.ToString().Trim();
            if (ValidateUtils.isUSZipCode(tmp))
            {
                if (tmp.Length > 5)
                {
                    tmp = tmp.Replace("-", string.Empty);
                    tmp = tmp.Substring(0, 5) + "-" + tmp.Substring(tmp.Length - 4, 4);
                }
            }
            return tmp.ToString();
        }

        /// <summary>
        /// Format US Phone. VD : (123) 123-1234
        /// </summary>
        /// <param name="s"></param>
        /// <returns></returns>
        public static string FormatUSPhone(object s, bool HasParenthesis)
        {
            string tmp = (s == null) ? string.Empty : s.ToString().Trim();

            if (ValidateUtils.isUSPhone(tmp))
            {
                tmp = stripCharsInBag(tmp, "()- ");
                if (HasParenthesis == true)
                    tmp = "(" + tmp.Substring(0, 3) + ") " + tmp.Substring(3, 3) + "-" + tmp.Substring(tmp.Length - 4, 4);
                else
                    tmp = tmp.Substring(0, 3) + "-" + tmp.Substring(3, 3) + "-" + tmp.Substring(tmp.Length - 4, 4);
            }
            return tmp.ToString();
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="o"></param>
        /// <param name="FormatLength"></param>
        /// <returns></returns>
        public static string FormatPhone(object o, char Separator, int FormatLength)
        {
            if (IsNullOrEmpty(o) == true)
                return string.Empty;

            string s = o.ToString();
            if (ValidateUtils.isNumberLetter(s) == true)
            {
                if (s.Length > FormatLength)
                    s = s.Substring(0, FormatLength) + Separator.ToString() + FormatPhone(s.Substring(FormatLength, s.Length - FormatLength), Separator, FormatLength);
            }
            return s;
        }


        /// <summary>
        /// Ham format so Social Security number cua Hoa Ky
        /// </summary>
        /// <param name="o"></param>
        /// <returns></returns>
        public static string FormatSSN(object o)
        {
            if (IsNullOrEmpty(o) == true)
                return string.Empty;
            string s = o.ToString();
            if (ValidateUtils.isSSN(s))
            {
                string tmp = s.ToString().Trim().Replace("-", "");
                return tmp.Substring(0, 3) + "-" + tmp.Substring(3, 2) + "-" + tmp.Substring(5, 4);
            }
            return s;
        }

        /// <summary>
        /// Ham dung de format Credit Card Expired Date. VD: 0302 -> March, 2002
        /// </summary>
        /// <param name="o"></param>
        /// <returns></returns>
        public static string FormatCreditCardExpiredDate(object o)
        {
            try
            {
                if (IsNullOrEmpty(o) == true)
                    return string.Empty;
                return DateTime.ParseExact(o.ToString(), "MMyy", null).ToString("MMM, yyyy");
            }
            catch
            {
                return o.ToString();
            }
        }

        /// <summary>
        /// Ham format DateTime va Number
        /// </summary>
        /// <param name="o">chuoi can format</param>
        /// <param name="FormatString">chuoi dinh dang</param>
        /// <returns></returns>
        public static string Format(object o, string FormatPattern)
        {
            if (IsNullOrEmpty(o) == true)
                return string.Empty;

            string tmp = string.Empty;
            try
            {
                if (o is DateTime)
                    tmp = ((DateTime)o).ToString(FormatPattern);
                else if (o is int)
                    tmp = ((int)o).ToString(FormatPattern);
                else if (o is long)
                    tmp = ((long)o).ToString(FormatPattern);
                else if (o is decimal)
                    tmp = ((decimal)o).ToString(FormatPattern);
                else if (o is double)
                    tmp = ((double)o).ToString(FormatPattern);
                else if (o is float)
                    tmp = ((float)o).ToString(FormatPattern);
                else
                    tmp = o.ToString();
            }
            catch
            {
                tmp = o.ToString();
            }
            return tmp.Trim();
        }
        #endregion

        #region payment
        public static string Payment_by_AUTHORIZE(string amount, string CCNumber, string CVVNumber, string expDate, string firstName, string lastName, string address, string zip, string city, string state, string country, out string error)
        {
            AuthorizeNetPaymentData pdata = new AuthorizeNetPaymentData();
            pdata.x_amount = amount;
            pdata.x_card_num = CCNumber;
            pdata.x_card_code = CVVNumber;
            pdata.x_exp_date = expDate;
            pdata.x_first_name = firstName;
            pdata.x_last_name = lastName;
            pdata.x_address = address;
            pdata.x_zip = zip;
            pdata.x_city = city;
            if (state.Equals(string.Empty) == false)
                pdata.x_state = state;
            pdata.x_country = country;

            string rsCC = AuthorizeNetPayment.PaymentAuthorizeNet(pdata, true);
            if (rsCC != null && rsCC.Length > 0 && rsCC[0].Equals('0'))//approved
            {
                error = string.Empty;
                return rsCC.Substring(2, rsCC.Length - 2);
            }
            else
            {
                error = AuthorizeNetPayment.GetValue(rsCC);
                return string.Empty;
            }
        }

        #endregion

        #region XML file and Text File
        /// <summary>
        /// 
        /// </summary>
        /// <param name="sXML"></param>
        /// <returns></returns>
        public static DataSet LoadDataFromXMLString(object sXML)
        {
            if (IsNullOrEmpty(sXML) == true)
                return null;

            DataSet ds = new DataSet();
            System.IO.StringReader sr = new System.IO.StringReader(sXML.ToString());
            ds.ReadXml(sr);
            return ds;
        }

        public static DataSet LoadDataFromXMLFile(string sFullPathFileName)
        {
            if (System.IO.File.Exists(sFullPathFileName) == false)
                return null;
            try
            {
                DataSet ds = new DataSet();
                ds.ReadXml(sFullPathFileName);
                return ds;
            }
            catch(Exception ex) { return null; }
        }

        public static string LoadDataFromTextFile(string sFullPathFileName)
        {
            if (System.IO.File.Exists(sFullPathFileName) == false)
                return string.Empty;
            try
            {
                return System.IO.File.ReadAllText(sFullPathFileName);
            }
            catch { return string.Empty; }
        }
        #endregion

        #region Logs
        /*
        private static log4net.ILog log = null;
        public static void WriteLogMessage(Exception ex)
        {
            string msg = "";
            if (ex != null)
            {
                msg += "\n" + ex.Message;
                msg += "\n" + ex.StackTrace;
            }
            if (msg != "") WriteLogMessage(msg);
        }

        public static void WriteLogMessage(Exception ex, Literal lt)
        {
            if (ex == null)
                return;

            string msg = string.Format("{0}\n\n{1}", ex.Message, ex.StackTrace);

            if (_database.ThrowException == false)
            {
                lt.Text = msg.Replace("\n", "<br>");
            }
            //else
            //{
            //    lt.Text = ex.Message;            
            //}
            WriteLogMessage(msg);
        }

        public static void WriteLogMessage(Exception ex, Label lb)
        {
            if (ex == null)
                return;

            string msg = string.Format("{0}\n\n{1}", ex.Message, ex.StackTrace);

            if (_database.ThrowException == false)
            {
                lb.Text = msg.Replace("\n", "<br>");
            }
            //else
            //{
            //    lb.Text = ex.Message;
            //}
            WriteLogMessage(msg);
        }

        public static void WriteLogMessage(string msg)
        {
            
            //if (FunctionsUtils.log == null) FunctionsUtils.log = log4net.LogManager.GetLogger(typeof(FunctionsUtils));
            //if (FunctionsUtils.log != null) FunctionsUtils.log.Debug(msg);
        }
        */
        #endregion

        #region Database, Message Error

        private static Database _database = null;
        public static Database Database
        {
            get
            {
                if (_database == null)
                {
                    _database = new Database(FunctionsUtils.GetConfigValue("ConnectionString"));
                    _database.ThrowException = ConvertToBool(FunctionsUtils.GetConfigValue("SiteDebug"), false);
                }
                return _database;
            }
        }

        /// <summary>
        /// dung de check DataSet co Null hay NoRecord
        /// </summary>
        /// <param name="ds"></param>
        /// <returns></returns>
        public static bool isDataSetNullOrEmpty(DataSet ds)
        {
            if (ds != null && ds.Tables.Count > 0 && ds.Tables[0].Rows.Count > 0)
                return false;
            return true;
        }

        private static MsgUtils _Msg = null;
        public static MsgUtils Msg
        {
            get
            {
                if (_Msg == null)
                    _Msg = new MsgUtils(FunctionsUtils.GetAppPath() + "XMLs\\Messages.xml");
                return _Msg;
            }
        }
        #endregion

        //#region ham dung chung trong current project
        //public static string GetAlbumUrl(object AlbumISN)
        //{
        //    if (FunctionsUtils.ConvertToInt(AlbumISN, 0) == 0)
        //        return string.Empty;

        //    string sPath = string.Empty;
        //    DataSet ds = FunctionsUtils.Database.ExecuteQuery("Select albAddedDate from Album Where AlbumISN=" + AlbumISN.ToString());

        //    if (FunctionsUtils.isDataSetNullOrEmpty(ds) == false)
        //    {
        //        DateTime date = Convert.ToDateTime(ds.Tables[0].Rows[0]["albAddedDate"]);
        //        //sPath = FunctionsUtils.GetConfigValue("AlbumUrl") + "/" + date.ToString("yyyyMM") + "/Albums/" + date.ToString("dd") + "/" + AlbumISN.ToString() + "/" ;
        //        sPath = string.Format("{0}/{1}/Albums/{2}/{3}/", FunctionsUtils.GetConfigValue("AlbumUrl"), date.ToString("yyyyMM"), date.ToString("dd"), AlbumISN);
        //    }
        //    return sPath;
        //}
        //public static string GetAlbumDir(object AlbumISN)
        //{
        //    if (FunctionsUtils.ConvertToInt(AlbumISN, 0) == 0)
        //        return string.Empty;

        //    string sPath = string.Empty;
        //    DataSet ds = FunctionsUtils.Database.ExecuteQuery("Select albAddedDate from Album Where AlbumISN=" + AlbumISN.ToString());

        //    if (FunctionsUtils.isDataSetNullOrEmpty(ds) == false)
        //    {
        //        DateTime date = Convert.ToDateTime(ds.Tables[0].Rows[0]["albAddedDate"]);
        //        //sPath = FunctionsUtils.GetConfigValue("AlbumUrl") + "/" + date.ToString("yyyyMM") + "/Albums/" + date.ToString("dd") + "/" + AlbumISN.ToString() + "/" ;
        //        sPath = string.Format("{0}\\{1}\\Albums\\{2}\\{3}\\", FunctionsUtils.GetConfigValue("AlbumUrl"), date.ToString("yyyyMM"), date.ToString("dd"), AlbumISN);
        //    }
        //    return sPath;
        //}

        //public static string GetAvataUrl(object isn)
        //{
        //    string s = "Images/imgNoImage.jpg";
        //    if (FunctionsUtils.ConvertToInt(isn, 0) > 0)
        //    {
        //        DataSet ds = FunctionsUtils.Database.ExecuteQuery("Select MemberISN, memSignUp, aglThumbnail From Vw_AngelFE Where MemberISN=" + isn.ToString());

        //        if (FunctionsUtils.isDataSetNullOrEmpty(ds) == false)
        //        {
        //            if (FunctionsUtils.IsNullOrEmpty(ds.Tables[0].Rows[0]["aglDisplayImage"]) == false)
        //            {
        //                DateTime date = Convert.ToDateTime(ds.Tables[0].Rows[0]["memSignUp"]);
        //                s = string.Format("{0}/{1}/Avatar/{2}/{3}", FunctionsUtils.GetConfigValue("AlbumUrl"), date.ToString("yyyyMM"), isn, ds.Tables[0].Rows[0]["aglDisplayImage"]);
        //            }
        //        }
        //    }
        //    return s;
        //}

        //public static string GetAvataUrl(object ISN, object memSignUp, object aglThumbnail)
        //{
        //    string s = "Images/imgNoImage.jpg";

        //    if (FunctionsUtils.IsNullOrEmpty(aglThumbnail) == false)
        //    {
        //        DateTime date = Convert.ToDateTime(memSignUp);
        //        s = string.Format("{0}/{1}/Avatar/{2}/{3}", FunctionsUtils.GetConfigValue("AlbumUrl"), date.ToString("yyyyMM"), ISN, aglThumbnail);
        //    }

        //    return s;
        //}

        //public static string getDisplayImage(string fileName, int position)
        //{
        //    string ext = Path.GetExtension(fileName);
        //    if (position == 1)
        //        return fileName.Replace(ext, "_1" + ext);
        //    else if (position == 2)
        //        return fileName.Replace(ext, "_2" + ext);
        //    else if (position == 3)
        //        return fileName.Replace(ext, "_3" + ext);
        //    else if (position == 4)
        //        return fileName.Replace(ext, "_4" + ext);
        //    else if (position == 5)
        //        return fileName.Replace(ext, "_5" + ext);

        //    return fileName;
        //}


        //public static string GetPhotoThumbnailName(string PhotoName)
        //{
        //    return System.IO.Path.GetFileNameWithoutExtension(PhotoName) + FunctionsUtils.GetConfigValue("ThumbnailName") + System.IO.Path.GetExtension(PhotoName);
        //}

        //public static bool CheckAngelOnline(int AngelISN, out string AngelUserName)
        //{
        //    AngelUserName = string.Empty;
        //    DataSet ds = FunctionsUtils.Database.ExecuteQuery("Select memUserName, aglStatus, ShowISN, FeeType, PayPerView From Vw_AngelFE Where MemberISN=" + AngelISN.ToString());
        //    if (FunctionsUtils.isDataSetNullOrEmpty(ds) == false)
        //    {
        //        AngelUserName = ds.Tables[0].Rows[0]["memUserName"].ToString();
        //        if (FunctionsUtils.ConvertToInt(ds.Tables[0].Rows[0]["aglStatus"], 0) == 1)
        //        {
        //            return true;
        //        }
        //    }
        //    return false;
        //}

        //public static string GetShow(object ShowISN, object AngelISN, object aglUserName, object FeeType, object PayPerView, string cssForLink)
        //{
        //    string s = string.Empty;// "I'm offline now.";
        //    string sHyperLinkViewShow = "Chat"; //<img hspace=\"5\" src=\"images/icoVideo1.png\" width=\"30\" height=\"30\">
        //    if (FunctionsUtils.IsNullOrEmpty(ShowISN) == false)
        //    {
        //        switch (FeeType.ToString())
        //        {
        //            case "0": //free
        //                //s = string.Format("<a href=\"javascript:OpenDialog('Dashboard','LiveShow.aspx?aisn={0}&sisn={1}',700,1024)\"><img hspace=\"5\" src=\"images/icoVideo1.png\" width=\"30\" height=\"30\"></a>", AngelISN, ShowISN);
        //                s = string.Format("<a href=\"javascript:OpenDialog('" + aglUserName + " Show','LiveShow.aspx?aisn={0}&sisn={1}',680,1120)\" class=\"{2}\">{3}</a>", AngelISN, ShowISN, cssForLink,sHyperLinkViewShow);
        //                break;
        //            case "1": //free with member login
        //                if (((User)HttpContext.Current.Session["UserInfo"]).UserISN == 0)
        //                {
        //                    //s = string.Format("<a href=\"javascript:confirmLiveShow({0},{1},{2},{3})\"><img hspace=\"5\" src=\"images/icoVideo1.png\" width=\"30\" height=\"30\"></a>", AngelISN, ShowISN, FeeType.ToString(), PayPerView.ToString());
        //                    s = string.Format("<a href=\"javascript:confirmLiveShow({0},{1},{2},{3})\" class=\"{4}\">{5}</a>", AngelISN, ShowISN, FeeType, PayPerView, cssForLink, sHyperLinkViewShow);
        //                }
        //                else
        //                {
        //                    //s = string.Format("<a href=\"javascript:OpenDialog('Dashboard','LiveShow.aspx?aisn={0}&sisn={1}',700,1024)\"><img hspace=\"5\" src=\"images/icoVideo1.png\" width=\"30\" height=\"30\"></a>", AngelISN, ShowISN);
        //                    s = string.Format("<a href=\"javascript:OpenDialog('" + aglUserName + " Show','LiveShow.aspx?aisn={0}&sisn={1}',680,1120)\" class=\"{2}\">{3}</a>", AngelISN, ShowISN, cssForLink, sHyperLinkViewShow);
        //                }
        //                break;
        //            case "2": //pay per view
        //            case "3": //private show
        //                if (((User)HttpContext.Current.Session["UserInfo"]).UserISN == 0)
        //                {
        //                    //s = string.Format("<a href=\"javascript:confirmLiveShow({0},{1},{2},{3})\"><img hspace=\"5\" src=\"images/icoVideo1.png\" width=\"30\" height=\"30\"></a>", AngelISN, ShowISN, 1, PayPerView.ToString());
        //                    s = string.Format("<a href=\"javascript:confirmLiveShow({0},{1},{2},{3})\" class=\"{4}\">{5}</a>", AngelISN, ShowISN, 1, PayPerView, cssForLink, sHyperLinkViewShow);
        //                }
        //                else
        //                {
        //                    s = string.Format("<a href=\"javascript:confirmLiveShow({0},{1},{2},{3})\" class=\"{4}\">{5}</a>", AngelISN, ShowISN, FeeType, PayPerView, cssForLink, sHyperLinkViewShow);
        //                }
        //                break;
        //        }

        //        s += " | ";
        //    }
        //    return s;
        //}

        //public static string GetAngelThumnailInfo(object angelISN, object angelUserName, object angelSignUp, object angelThumnail, object showISN, object feeType, object payPerView, string cssForContainer, string cssForDivImage, string cssForDivInfo, string cssForHyperlink)
        //{
        //    string s = string.Empty;
        //    //s = string.Format("<div class='{0}'><div class='{1}'><img src='{2}'></div><div class='{3}'><a href='#' class='{4}'>{5}</a><br>{6}<a href='AngelProfile.aspx?aisn={7}' class='{4}'>profile</a></div></div>", cssForContainer, cssForDivImage, GetAngelAvatarUrl(angelISN, angelSignUp, angelThumnail, 1), cssForDivInfo, cssForHyperlink, angelUserName, FunctionsUtils.GetShow(showISN, angelISN, feeType, payPerView, cssForHyperlink), angelISN);
        //    s = string.Format("<div class='{0}'><div class='{1}'><img src='{2}'></div><div class='{3}'>{4}<br>{5}<a href='AngelProfile.aspx?aisn={6}' class='{7}'>profile</a></div></div>", cssForContainer, cssForDivImage, GetAngelAvatarUrl(angelISN, angelSignUp, angelThumnail, 2), cssForDivInfo, angelUserName, FunctionsUtils.GetShow(showISN, angelISN, angelUserName, feeType, payPerView, cssForHyperlink), angelISN, cssForHyperlink);
        //    return s;
        //}

        //public static string GetAngelAvatarUrl(object ISN, object memSignUp, object aglThumbnail, int imageSize)
        //{
        //    string s = string.Format("Images_new/imgNoPhoto_{0}.jpg", imageSize);

        //    if (FunctionsUtils.IsNullOrEmpty(aglThumbnail) == false)
        //    {
        //        DateTime date = Convert.ToDateTime(memSignUp);
        //        string file = string.Format("{0}\\{1}\\Avatar\\{2}\\{3}", FunctionsUtils.GetConfigValue("AlbumDir"), date.ToString("yyyyMM"), ISN, getImageSize(aglThumbnail, imageSize));
        //        if (File.Exists(file))
        //            s = string.Format("{0}/{1}/Avatar/{2}/{3}", FunctionsUtils.GetConfigValue("AlbumUrl"), date.ToString("yyyyMM"), ISN, getImageSize(aglThumbnail, imageSize));
        //    }

        //    return s;
        //    //return "Images_New/imgthumb.jpg";
        //}

        //public static string getImageSize(object imageFileName, int imageSize)
        //{
        //    string s = string.Empty;
        //    if (FunctionsUtils.IsNullOrEmpty(imageFileName) == false)
        //    {
        //        s = string.Format("{0}_{1}{2}", System.IO.Path.GetFileNameWithoutExtension(imageFileName.ToString()), imageSize, System.IO.Path.GetExtension(imageFileName.ToString()));
        //    }
        //    return s;
        //}

        //public static string getOnlineFriends(int userISN)
        //{
        //    string s = string.Empty;

        //    if (userISN > 0)
        //    {
        //        //s = "<div class='imgthumb1'><img src='Images_New/imgAvatar1.jpg' width='34' height='33' alt='' /></div>";
        //        s = "<div class='txtcontent1'>No Friend</div>";

        //        /*
        //                <div class="imgthumb1"><img src="Images_New/imgAvatar1.jpg" width="34" height="33" alt="" /></div>
        //                <div class="imgthumb1"><img src="Images_New/imgAvatar2.jpg" width="34" height="33" alt="" /></div>
        //                <div class="imgthumb1"><img src="Images_New/imgAvatar3.jpg" width="34" height="33" alt="" /></div>
        //                <div class="imgthumb1"><img src="Images_New/imgAvatar4.jpg" width="34" height="33" alt="" /></div>
        //                <div class="imgthumb1"><img src="Images_New/imgAvatar5.jpg" width="34" height="33" alt="" /></div>
        //                <div class="imgthumb1"><img src="Images_New/imgAvatar1.jpg" width="34" height="33" alt="" /></div>
        //                <div class="imgthumb1"><img src="Images_New/imgAvatar4.jpg" width="34" height="33" alt="" /></div>
        //         */
        //    }
        //    else
        //    {
        //        s = "<div class='txtcontent1'>No Friend</div>";
        //    }
        //    return s;
        //}

        //public static string getPopularRooms(int userISN)
        //{
        //    string s = "<div class='txtcontent1'>RECENTLY VISITED<br />&nbsp;No Angel</div>"; //string.Empty;
        //    if (userISN > 0)
        //    {
        //        DataSet ds = FunctionsUtils.Database.ExecuteStoredProcReturnDataSet("xp_member_lastangel",
        //            new string[] { "MemberISN" }, new object[] { userISN });
        //        if (FunctionsUtils.NotEmpty(ds))
        //        {
        //            s = "<div class='txtcontent1'>RECENTLY VISITED";
        //            foreach (DataRow row in ds.Tables[0].Rows)
        //            {
        //                s += "<br />- " + row["memUserName"].ToString();
        //            }
        //            s += "</div>";
        //        }
        //    }
        //    return s;
        //}

        //public static string getFeaturedAngels()
        //{
        //    string s = string.Empty;

        //    DataSet ds = FunctionsUtils.Database.ExecuteQuery("select top 7 * from Vw_AngelBestView order by TotalViewing desc");

        //    if (FunctionsUtils.isDataSetNullOrEmpty(ds) == false)
        //    {
        //        for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
        //        {
        //            s += FunctionsUtils.GetAngelThumnailInfo(ds.Tables[0].Rows[i]["MemberISN"], ds.Tables[0].Rows[i]["memUserName"], ds.Tables[0].Rows[i]["memSignUp"], ds.Tables[0].Rows[i]["aglDisplayImage"], ds.Tables[0].Rows[i]["ShowISN"], ds.Tables[0].Rows[i]["FeeType"], ds.Tables[0].Rows[i]["PayPerView"], "thumbcontent", "imgthumb", "thumbdes", "url2");
        //            /*
        //                <div class="thumbcontent">
        //                    <div class="imgthumb"><img src="Images_New/imgthumb.jpg" width="94" height="109" alt="" /></div>
        //                    <div class="thumbdes">
        //                        <a href="#" class="url2">jessica</a><br />
        //                        <a href="#" class="url2" style="float:left">chat</a> | <a href="#" class="url2" style="float:right">profile</a></div>
        //                </div>                 
                 
        //             */
        //        }

        //        if (ds.Tables[0].Rows.Count < 7)
        //        {
        //            for (int i = 0; i < (7 - ds.Tables[0].Rows.Count); i++)
        //            {
        //                s += "<div class='thumbcontent'></div>";
        //            }
        //        }
        //    }
        //    else
        //    {
        //        //s = "No angel online";
        //        for (int i = 0; i < 7; i++)
        //        {
        //            s += "<div class='thumbcontent'></div>";
        //        }

        //    }
        //    return s;
        //}

        //public static string getUserPaymentInfo(User user)
        //{
        //    string s = string.Empty;

        //    if (user.UserISN > 0)
        //    {
        //        s = string.Format("<strong>Hello,</strong> {0}</div><div class='box4'><a href='#' class='url9'>500 Tokens</a><br><a href='javascript:' onclick=\"OpenDialog('Purchase Tokens','RechargeMonth.aspx',670,580)\" class='url9'>Purchase Tokens</a><br><a href='#' class='url9'>Admin</a>", user.UserName);
        //    }
        //    return s;
        //}

        //public static DataSet GetUserLoginInfo(string Email, string Password, out int Result)
        //{
        //    string[] names = new string[] { "Email", "Password" };
        //    object[] values = new object[] { Email, Password };
        //    return FunctionsUtils.Database.ExecuteStoredProcReturnDataSet("xp_member_login", names, values, out Result);
        //}

        //public static bool CheckDataLogin(string email, string password, Literal lt)
        //{
        //    bool bResult = true;
        //    bool bFormat = true;
        //    string s = string.Empty;

        //    if (email.Trim().Length == 0)
        //    {
        //        s = "Email ";
        //        bResult = false;
        //    }
        //    else
        //    {
        //        if (ValidateUtils.isEmail(email.Trim()) == false)
        //        {
        //            s = string.Format(FunctionsUtils.Msg["frm_Format2"], "Your email");
        //            bResult = false;
        //            bFormat = false;
        //        }
        //    }

        //    if (password.Trim().Length == 0)
        //    {
        //        s += (s.Length > 0 ? "and " : string.Empty) + "Password ";
        //        bResult = false;
        //    }

        //    if (bResult == false && bFormat == true)
        //        s += "required.<br>";

        //    lt.Text = s;

        //    return bResult;
        //}

        //#endregion

        #region JavaScript
        private static string getjQueryCode(string jsCodetoRun)
        {
            System.Text.StringBuilder sb = new System.Text.StringBuilder();
            sb.AppendLine("$(document).ready(function(){");
            sb.AppendLine(jsCodetoRun);
            sb.AppendLine("});");
            return sb.ToString();
        }

        /// <summary>
        /// dung de call javascript function with jQuery
        /// </summary>
        /// <param name="jsCodetoRun"></param>
        /// <param name="oPage"></param>
        public static void runjQueryCode(string jsCodetoRun, System.Web.UI.Page oPage)
        {
            ScriptManager requestSM = ScriptManager.GetCurrent(oPage);
            if (requestSM != null && requestSM.IsInAsyncPostBack)
            {
                ////ScriptManager.RegisterClientScriptBlock(oPage,
                ////                                        typeof(Page),
                ////                                        Guid.NewGuid().ToString(),
                ////                                        getjQueryCode(jsCodetoRun),
                ////                                        true);
                ScriptManager.RegisterStartupScript(oPage,
                                                    typeof(Page),
                                                    Guid.NewGuid().ToString(),
                                                    getjQueryCode(jsCodetoRun),
                                                    true);
            }
            else
            {
                //oPage.ClientScript.RegisterClientScriptBlock(typeof(Page),
                //                                       Guid.NewGuid().ToString(),
                //                                       getjQueryCode(jsCodetoRun),
                //                                       true);
                oPage.ClientScript.RegisterStartupScript(typeof(Page),
                                                       Guid.NewGuid().ToString(),
                                                       getjQueryCode(jsCodetoRun),
                                                       true);
            }
        }
        #endregion

        //public static int PageCount(int TotalRecords, int PageSize)
        //{
        //    int Total = 0;
        //    if (PageSize > 0)
        //    {
        //        Total = TotalRecords / PageSize;
        //        if (TotalRecords % PageSize > 0)
        //        {
        //            Total += 1;
        //        }
        //    }
        //    return Total;
        //}

        public static int PageCount(int recordCount, int pageSize)
        {
            try
            {
                return (int)Math.Ceiling((double)recordCount / pageSize);
            }
            catch
            {
                return 1;
            }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="currPage"></param>
        /// <param name="pageCount"></param>
        /// <returns></returns>
        public static int GetCurrPage(int currPage, int pageCount)
        {
            if (currPage <= 0)
            {
                currPage = 1;
            }
            else if (currPage > pageCount)
            {
                currPage = pageCount;
            }

            return currPage;
        }

        #region Dataset
        public static bool IsEmpty(string s)
        {
            return s == null || s.Trim() == string.Empty;
        }
        public static bool IsEmpty(DataSet ds)
        {
            return ds == null || ds.Tables.Count == 0 || ds.Tables[0].Rows.Count == 0;
        }
        public static bool IsEmpty(DataTable table)
        {
            return table == null || table.Rows.Count == 0;
        }
        public static bool NotEmpty(DataSet ds)
        {
            return ds != null && ds.Tables.Count > 0 && ds.Tables[0].Rows.Count > 0;
        }
        public static bool NotEmpty(DataTable table)
        {
            return table != null && table.Rows.Count > 0;
        }
        #endregion

        public static string GetStatus(object value)
        {
            int statusCode = ConvertToInt(value, 0);

            if (statusCode == 1)
                return "Yes";
            else
                return "No";
        }
    }
}